package cn.pink.gamesrv;

import cn.pink.common.proto.Msg;
import cn.pink.core.*;
import cn.pink.core.gen.proxy.DistrClass;
import cn.pink.core.gen.proxy.DistrMethod;
import cn.pink.core.support.Param;
import cn.pink.gamesrv.human.HumanGlobal;
import cn.pink.gamesrv.human.HumanObjectService;
import cn.pink.gatesrv.RPCProxy.SessionServiceProxy;
import io.vertx.core.Future;
import io.vertx.core.Promise;

/**
 * @Author: pink
 * @Date: 2022/6/21 16:50
 */
@DistrClass(nodeType = NodeType.GAME, importClass = {CallPoint.class})
public class GameService extends Service {
    public GameService(Port port) {
        super(port);
    }

    @Override
    public Object getId() {
        return RPCProxy.GameServiceProxy.DIST_NAME;
    }

    @DistrMethod
    public Param defaultHandler(String str) {
        return null;
    }

    @DistrMethod(isReturnAsync = true)
    public Future<Param> roleLogin(CallPoint sessionPoint, String humanId, String userIdentity, String token) {
        Promise<Param> promise = Promise.promise();

        //先判断下本服上有没有HumanObjectService
        HumanObjectService service = getPort().getService(humanId);
        if(service != null) {
            //有直接复用之前的human. 更改sessionPoint, 不然玩家换gate回不去消息.
            service.changeSessionPoint(sessionPoint);

            loginFinish(service, sessionPoint);

            promise.complete();

            return promise.future();
        }

        HumanObjectService humanObjServ = new HumanObjectService(port);
        humanObjServ.login(sessionPoint, humanId, userIdentity, token).onSuccess(v -> {
            loginFinish(humanObjServ, sessionPoint);
            HumanGlobal.register(humanObjServ);

            promise.complete();
        });

        return promise.future();
    }

    private void loginFinish(HumanObjectService service, CallPoint sessionPoint) {
        // 成功协议
        Msg.SCRoleLogin.Builder msg = Msg.SCRoleLogin.newBuilder();
        msg.setResultCode(0);

        // 发送并绑定
        SessionServiceProxy proxy = SessionServiceProxy.newInstance(sessionPoint);
        proxy.loginResult(service.getHumanObj().getId(), service.getCallPoint(), new Chunk(msg));

        service.getHumanObj().loginFinish();

        //            EventSubject.fire(EventKey.ACCOUNT_LOGIN, new Param(humanId));
    }
}
